#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
import argparse
import uvicorn
from core import Logger, Config
from core.app import create_app
from core.tasks import dlApp
from dotenv import load_dotenv
import asyncio
import logging

from celery import Celery  
from celery.bin import worker  

def start_worker(args, argv):
    # Start the worker
    logLevel = "INFO"
    if Config.DEBUG:
        logLevel = "DEBUG"
    argv = [
        '-A',
        'core.tasks',
        'worker',
        f'--loglevel={logLevel}',
        f'--concurrency={args.concurrency}',
        # f'--pool=threads'
    ]
    dlApp.start(argv=argv)
# async函数，用于定义异步的函数
def serve(args, argv):
    app = create_app()
    # 打印启动服务器的信息
    print(f"> Start API server... 0.0.0.0:{Config.APP_PORT}")
    uvicorn.run(app, host="0.0.0.0", port=Config.APP_PORT)

def main():
    load_dotenv()
    parser = argparse.ArgumentParser(
        description='distdl server')

    sub_parsers = parser.add_subparsers(help='sub commands')
    parser_serve = sub_parsers.add_parser('serve', help="start api server")
    parser_serve.set_defaults(func=serve)

    parser_worker = sub_parsers.add_parser('worker', help="start worker")
    parser_worker.add_argument('--concurrency', '-c', type=int, default=4, help=" Number of child processes processing the queue.  The default is the number of CPUs available on your system.", required=False)
    parser_worker.set_defaults(func=start_worker)

    args,argv = parser.parse_known_args()
    #setup logging
    console_handler = logging.StreamHandler()
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    console_handler.setFormatter(formatter)
    Logger.addHandler(console_handler)
    if Config.DEBUG:
        Logger.setLevel(logging.DEBUG)
    else:
        Logger.setLevel(logging.ERROR)
    Logger.debug(f"begin start dcrawler")
    if hasattr(args, 'func'):  
        args.func(args, argv)
    else:  
        parser.print_help()  
        return 1

if __name__ == "__main__":
    main()